﻿using FastCloud.Base.Config;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FastCloud.Base
{
    public class CloudControllerActivator : IControllerActivator
    {
        public object Create(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.ActionDescriptor == null)
            {
                throw new ArgumentException(nameof(ControllerContext.ActionDescriptor));
            }

            var controllerTypeInfo = context.ActionDescriptor.ControllerTypeInfo;

            if (controllerTypeInfo == null)
            {
                throw new ArgumentException(nameof(context.ActionDescriptor.ControllerTypeInfo));
            }

            Type controllerType = PluginManage.GetControllerType(context.ActionDescriptor.ControllerName + "Controller");
            if (controllerType==null)
            {
                controllerType = controllerTypeInfo.AsType();
            }
            return InjectContext.Resolve(controllerType);
        }

        public void Release(ControllerContext context, object controller)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            var disposable = controller as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }

        }
    }
}
